package org.jboss.as.quickstarts.login.stripes;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.jboss.as.quickstarts.login.User;
import org.jboss.as.quickstarts.login.UserManager;

import javax.inject.Inject;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Gregory Rushton, gregory.rushton@gmail.com
 *         Date: 9/7/11
 *         Time: 9:59 AM
 */
@UrlBinding("/Stripes/AddUser.action")
public class AddUserActionBean extends BaseActionBean {

    @Inject
    private UserManager userManager;

    @Inject
    private transient Logger logger;

    @ValidateNestedProperties({
            @Validate(field = "name", required = true, on = {"addUser"}),
            @Validate(field = "username", required = true, on = {"addUser"}),
            @Validate(field = "password", required = true, on = {"addUser"})
    })
    private User user;

    public User getUser() {
        return user;
    }

    @SuppressWarnings({"unused"})
    public void setUser(User user) {
        this.user = user;
    }

    @HandlesEvent("addUser")
    public Resolution addUser() {
        try {
            userManager.addUser(getUser());
            getContext().getMessages().add(new SimpleMessage("Added user: " + getUser().toString()));
        } catch (Exception e) {
            logger.log(Level.ALL, "Exception adding user: " + getUser().toString());
            getContext().getValidationErrors().addGlobalError(new SimpleError("Sorry, Exception adding user: " + getUser().toString()));
        }
        return new ForwardResolution(UsersActionBean.class);
    }

}
